var WGS84ToSH;

require([
    "esri/symbols/PictureMarkerSymbol",
    "esri/graphic"
], function (PictureMarkerSymbol, Graphic) {

    //坐标检索,输入城建坐标定位
    $("#xyLocationSearchBtn0").click(function () {
        thematicGraphicLayer.clear();
        var x = parseFloat($("#xInput0").val());
        var y = parseFloat($("#yInput0").val());
        if (!isNaN(x) && !isNaN(y)) {
            var point = new esri.geometry.Point(x, y, map.spatialReference);
            var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
            var graphic = new Graphic(point, sms);
            thematicGraphicLayer.add(graphic);
            map.centerAndZoom(point, 6);
        } else if (isNaN(x) && !isNaN(y)) {
            warningAlert("请输入x坐标");
        } else if (isNaN(y) && !isNaN(x)) {
            warningAlert("请输入y坐标");
        } else {
            warningAlert("请输入X坐标和y坐标");
        }
    });

    $("#xyLocationResetBtn0").click(function () {
        thematicGraphicLayer.clear();
        $("#xInput0").val('');
        $("#yInput0").val('');
    });

    $("#yInput0").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#xyLocationSearchBtn0").click();
        }
    })

    //坐标检索，WGS84
    $("#xyLocationSearchBtn1").click(function () {
        thematicGraphicLayer.clear();
        var lng = parseFloat($("#xInput1").val());
        var lat = parseFloat($("#yInput1").val());

        if (!isNaN(lng) && !isNaN(lat)) {
            WGS84ToSH(lng, lat, '检索').then(resolve => {})
        } else if (isNaN(lat) && !isNaN(lng)) {
            warningAlert("请输入经度");
        } else if (isNaN(lng) && !isNaN(lat)) {
            warningAlert("请输入纬度");
        } else {
            warningAlert("请输入经度和纬度");
        }
    });

    $("#xyLocationResetBtn1").click(function () {
        thematicGraphicLayer.clear();
        $("#xInput1").val('');
        $("#yInput1").val('');
    });

    $("#yInput1").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#xyLocationSearchBtn1").click();
        }
    })

    //坐标转换，84->上海，单点转换
    $("#coordTransferPanelSearchBtn1").click(function () {
        thematicGraphicLayer.clear();
        var lng = parseFloat($("#tlngInput1").val());
        var lat = parseFloat($("#tlatInput1").val());

        if (!isNaN(lng) && !isNaN(lat)) {
            WGS84ToSH(lng, lat, '转换').then(resolve => {})
        } else if (isNaN(lat) && !isNaN(lng)) {
            warningAlert("请输入经度");
        } else if (isNaN(lng) && !isNaN(lat)) {
            warningAlert("请输入纬度");
        } else {
            warningAlert("请输入经度和纬度");
        }
    });

    $("#coordTransferPanelResetBtn1").click(function () {
        thematicGraphicLayer.clear();
        $("#txInput1").val('');
        $("#tyInput1").val('');
        $("#tlngInput1").val('');
        $("#tlatInput1").val('');
    });

    $("#tlatInput1").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#coordTransferPanelSearchBtn1").click();
        }
    })


    //批量地址转换按钮点击事件
    $("#coordTransferPanelSearchBtn2").click(() => {
        var title0 = $("#coordTransferPanel").find(".file-caption-name")[0].title;

        if (title0 != "") {
            $("#coordTransferPanel").find(".fileinput-upload")[0].click();
        } else {
            warningAlert("请选择坐标转换文件");
        }
    })

    //坐标转换文件解析结果
    $("#coordTransferFileUpload0_iframeContent").on("load", function () {
        var responseText = $("#coordTransferFileUpload0_iframeContent")[0].contentDocument.body.getElementsByTagName("pre")[0].innerHTML;

        const layerListType = "coordTransferLayerList";

        var fileNameWithExt;

        var index = responseText.lastIndexOf(".");
        var ext = responseText.substr(index + 1);

        if (responseText.substr(responseText.length - 1, 1) == "}") {
            if (responseText == '{}') {
                failAlert("您加载的excel无内容，请检查后重新上传！");
            } else {
                resultJSON = eval('(' + responseText + ')');
                fileNameWithExt = resultJSON.fileName + ".xls";
                localFileName = fileNameWithExt + "的坐标转换结果";
            }
        } else if (ext == "csv") {
            fileNameWithExt = responseText;
            localFileName = fileNameWithExt + "的坐标转换结果";
        }

        fileParse(responseText, layerListType);

        doMultiCoordTransfer(selectedGraphicArr, fileNameWithExt, layerListType)
    });

    function doMultiCoordTransfer(selectedGraphicArr, fileNameWithExt, layerListType) {
        let coordTransferResult = [];
        matchGraphics = [];
        matchGeometries = [];

        infoNotify('坐标批量转换中，请稍后...');

        //防止浏览器限制websocket连接数量，每次发送300个请求
        let splitSelectedGraphicArr = splitArr(selectedGraphicArr, 300);

        let splitSelectedGraphicArrLength = splitSelectedGraphicArr.length;
        //递归splitTextsLength次

        let postPromise = num => {
            let splitArr = splitSelectedGraphicArr[num];
            for (let i = 0; i < splitArr.length; i++) {
                let x = splitArr[i].geometry.x;
                let y = splitArr[i].geometry.y;
                coordTransferResult.push(WGS84ToSH(x, y, "批量转换", splitArr[i].attributes));
            }

            Promise.all(coordTransferResult).then(() => {
                num++;

                if (num < splitSelectedGraphicArrLength) {
                    postPromise(num);
                } else {
                    if (matchGeometries.length == 0) {
                        warningAlert("无可转换的坐标！")
                    } else {
                        setBufferParams(matchGraphics);
                        createFeatureLayer(matchGraphics, fileNameWithExt + "的坐标转换结果", layerListType);
                    }
                }
            }, () => {});
        }

        //调用地址匹配的promise请求
        postPromise(0);
    }


    //返回值中的XY是测量平面直角坐标系，和数学中的笛卡尔坐标系的XY相反
    WGS84ToSH = (lng, lat, type, attributes) => {
        const promise = new Promise((resolve, reject) => {
            // var OneMapHost = 'http://map.smi.sh.cegn.cn';
            var OneMapHost = oneMapServerIP+'';

            var sr = '<?xml version="1.0" encoding="utf-8"?>';
            sr += '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
            sr += '<soap:Body><WGS84BLH2SH xmlns="SHCoordTransM1WS"><arg0 xmlns="">' + lat * Math.PI / 180 + '</arg0><arg1 xmlns="">' + lng * Math.PI / 180 + '</arg1><arg2 xmlns="">0</arg2></WGS84BLH2SH></soap:Body></soap:Envelope>';

            let coordObj = {}
            $.ajax({
                url: OneMapHost + "/OneMapServer/rest/services/coordtransm1ws/Transfer?token=" + GLOBAL_TOKEN,
                type: "post",
                // async: false,
                dataType: "XML",
                data: sr,
                xhrFields: {
                    withCredentials: true
                },
                headers: {
                    "Content-Type": "text/xml;charset=utf-8"
                },
                success: function (response) {
                    var coord = [];

                    if (null != response.getElementsByTagName("return")[0] && response.getElementsByTagName("return")[0].textContent != null && null != response.getElementsByTagName("return")[1] && response.getElementsByTagName("return")[1].textContent != null) {
                        coord[0] = parseFloat(response.getElementsByTagName("return")[0].textContent).fixed(2);
                        coord[1] = parseFloat(response.getElementsByTagName("return")[1].textContent).fixed(2);

                    } else {
                        return
                    }

                    // var y = parseFloat(coord[0]);
                    // var x = parseFloat(coord[1]);

                    // coordObj = {
                    //     x,
                    //     y
                    // }

                    // resolve(coordObj);

                    if (type == '转换') {
                        document.getElementById("tyInput1").value = coord[0];
                        document.getElementById("txInput1").value = coord[1];
                        resolve();

                    } else if (type == '检索') {
                        var y = parseFloat(coord[0]);
                        var x = parseFloat(coord[1]);

                        var point = new esri.geometry.Point(x, y, map.spatialReference);
                        var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
                        var graphic = new Graphic(point, sms);
                        thematicGraphicLayer.add(graphic);
                        map.centerAndZoom(point, 6);
                        resolve();

                    } else if (type == '批量转换') {
                        var y = coord[0];
                        var x = coord[1];
                        attributes["原始经度"] = lng;
                        attributes["原始纬度"] = lat;
                        attributes["转换后x坐标"] = x;
                        attributes["转换后y坐标"] = y;

                        var point = new esri.geometry.Point(x, y, map.spatialReference);
                        var graphic = new Graphic(point, null, attributes);

                        matchGraphics.push(graphic);
                        matchGeometries.push(point);

                        resolve();
                    } else if (type == '批量转换线面') {
                        var y = coord[0];
                        var x = coord[1];
                        
                        // attributes["原始经度"] = lng;
                        // attributes["原始纬度"] = lat;
                        // attributes["转换后x坐标"] = x;
                        // attributes["转换后y坐标"] = y;

                        // var point = new esri.geometry.Point(x, y, map.spatialReference);
                        // var graphic = new Graphic(point, null, attributes);

                        // matchGraphics.push(graphic);
                        // matchGeometries.push(point);

                        resolve();
                    }
                },
                error: function () {
                    reject()
                }
            });
            // return coordObj
        })

        return promise;
    }

});